package model

import (
	"gopkg.in/mgo.v2/bson"
	"src/util/security"
)

type Admin struct {
	ID     bson.ObjectId `bson:"_id,omitempty" json:"id,omitempty"`
	Name   string        `bson:"name" json:"name"`
	HashPW string        `bson:"hash_pw" json:"hash_pw"`
}

func CreatAdmin(name, pwd string) error {
	admin := Admin{}
	admin.Name = name
	hashPW, err := security.HashPassword(pwd)
	if err != nil {
		return err
	}
	admin.HashPW = hashPW
	err = insertAdmin(admin)
	if err != nil {
		return err
	}
	return nil
}

func CheckAdminInfo(username, password string) (bool, error) {
	query := bson.M{
		"username": username,
	}
	admin, err := findAdmin(query, DefaultSelector)
	if err != nil {
		return false, err
	}
	return security.CheckPasswordHash(password, admin.HashPW), nil
}

func FindAdmin(name string) (Admin, error) {
	query := bson.M{
		"name": name,
	}
	a, err := findAdmin(query, DefaultSelector)
	return a, err
}

/*****************************************************************************/
func insertAdmin(docs ...interface{}) error {
	sess := globalSess.Clone()
	defer sess.Close()
	AdminTable := sess.DB(DBNAME).C(ADMINTABLE)

	return AdminTable.Insert(docs...)
}
func findAdmin(query, selector interface{}) (Admin, error) {
	sess := globalSess.Copy()
	defer sess.Close()
	AdminTable := sess.DB(DBNAME).C(ADMINTABLE)

	Admin := Admin{}
	err := AdminTable.Find(query).Select(selector).One(&Admin)
	return Admin, err
}
